<template>
  <div class="login-container">
    <div class="login-box">
      <h2>登录</h2>
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username" autocomplete="off" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password" type="password" autocomplete="off" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin" :loading="loading" style="width: 100%;">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {httpRequest} from '@/service/http' 
const router = useRouter()
const loginFormRef = ref(null)
const loading = ref(false)
const loginForm = ref({
  username: '',
  password: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

const handleLogin = async () => {
  loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      // 模拟登录请求
      await setTimeout(() => {
        httpRequest.testLogin({userName:loginForm.value.username,password:loginForm.value.password})
          .then(res=>{
            console.log(res)
            if(res.code===200){//登陆成功
              sessionStorage.token = res.data.token
              sessionStorage.userName = res.data.userName
              console.log('登录成功,token值为',sessionStorage.token,'欢迎用户',sessionStorage.userName)
              ElMessage.success('登录成功')
              router.push('/')
            }else{
              ElMessage.error(res.message || '登录失败,请重试')
            }
          })
          .catch(err=>{
            console.error('登录错误:', err)
            ElMessage.error(err.message || '登录失败，请重试')
          })
        loading.value = false
      }, 1000)
    }
  })
}
</script>

<style scoped>
.login-container {
  width: 100vw;
  height: 100vh;
  background: #f0f2f5;
  display: flex;
  align-items: center;
  justify-content: center;
}
.login-box {
  width: 350px;
  padding: 40px 30px 30px 30px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}
.login-box h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}
</style>
